import { ref } from 'vue'
import { updatepassword } from '@/apis/manager.js'
import { toast } from '@/composables/util'
import { useRouter } from 'vue-router'
import { removeToken } from '@/composables/auth'
import { useUserStore } from '@/store/index.js'

const router = useRouter()

// 封装修改密码操作
export const useRepassword = () => {
  const userStore = useUserStore()
  

  //ref模版引用获取FormDrawer组件实例
  const formDrawerRef = ref(null)

  const form = ref({
    oldpassword: '',
    password: '',
    repassword: ''
  })

  const rules = ref({
    // 触发方式 blur 元素失去焦点时触发
    oldpassword: [
      { required: true, message: '旧密码不能为空', trigger: 'blur' },
      { min: 3, max: 5, message: '长度应该是3到5个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '新密码不能为空', trigger: 'blur' },
      { min: 3, max: 5, message: '长度应该是3到5个字符', trigger: 'blur' }
    ],
    repassword: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      { min: 3, max: 5, message: '长度应该是3到5个字符', trigger: 'blur' }
    ]
  })

  //修改密码
  const formRef = ref(null)
  const onSubmit = () => {
    // 调用validate方法
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      // 通过校验，登录之前将登录按钮状态设置为 登录中 状态
      formDrawerRef.value.showLoading()
      updatepassword(form.value)
        .then(() => {
          toast('修改密码成功，请重新登录')
          //退出登录逻辑：
          // 跳转回登录页(编程式路由导航)
          router.push('/login')
          // 移除cookie
          removeToken()
          // 清除pinia中用户状态
          userStore.user.value = {}
        })
        .finally(() => {
          //登录之后将登录按钮状态设置为 登录 状态
          formDrawerRef.value.hideLoading()
        })
    })
  }

  //显示窗体
  const openRePasswordForm = () => formDrawerRef.value.open()

  return {
    formDrawerRef,
    formRef,
    form,
    rules,
    onSubmit,
    openRePasswordForm
  }
};